<?php
namespace app\service\sys;

/**
 * 公共工具方法
 * 
 * @method void getCurrentUrl: 获取当前url.
 * @method void getRealClientIP: 获取真实ip.
 * @method void generateSMSCode: 随机数生成工具.
 * 
 *
 * @package     app\common\service
 * @author      陈浩/陈浩 <lilts@qq.com>
 * @version     1.0.0
 * @since       PHP 8.2
 * @license     MIT（或自定义协议）
 */
class ToolService
{

    /**
     * 获取当前url
     * 
     * @param boolean $returnArray: 返回数组。 [选填]  [默认：false]
     * 
     * @return string|array: 返回当前url地址
     * 
     * */
    public static function getCurrentUrl($returnArray = false): string|array {
        $scheme = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'] ?? '';
        $uri = $_SERVER['REQUEST_URI'] ?? '';

        // 处理非标准端口
        if (isset($_SERVER['SERVER_PORT']) && !in_array($_SERVER['SERVER_PORT'], [80, 443])) {
            $host = str_replace(':' . $_SERVER['SERVER_PORT'], '', $host) . ':' . $_SERVER['SERVER_PORT'];
        }
        if ($returnArray) {
            return [
                'scheme' => $scheme,
                'host' => $host,
                'uri' => $uri,
                'url' => $scheme . $host . $uri,
            ];
        }
        return $scheme . $host . $uri;
    }

    /**
     * 获取真实ip
     * 
     * @return string: 返回ip地址
     * 
     */
    public static function getRealClientIP(): string {
        $ip = $_SERVER['REMOTE_ADDR'] ?? '';
        $headersToCheck = [
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR'
        ];

        foreach ($headersToCheck as $header) {
            if (!empty($_SERVER[$header])) {
                $ipList = explode(',', $_SERVER[$header]);
                foreach ($ipList as $candidateIp) {
                    $trimmedIp = trim($candidateIp);
                    if (filter_var($trimmedIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                        $ip = $trimmedIp;
                        break 2;
                    }
                }
            }
        }
        return $ip;
    }

    /**
     * 随机数生成工具
     * 
     * @param int $length: 随机数长度。 [选填]  [默认：4]
     * @param string $characters: 随机数使用字符。 [默认纯数字：0123456789]
     *
     * @return string: 随机数字符串
     *
     */
    public static function generateSMSCode(
        int $length = 4,
        string $characters = '0123456789'
    ): string {
        $code = '';
        $max = strlen($characters) - 1;

        for ($i = 0; $i < $length; $i++) {
            $code .= $characters[random_int(0, $max)];
        }

        return $code;
    }
    
}